import { Injectable } from '@nestjs/common'
import { CreateVisitDto } from './dto/create-visit.dto'
import { UpdateVisitDto } from './dto/update-visit.dto'
import { PrismaService } from '../prisma/prisma.service'

@Injectable()
export class VisitService {
    constructor(private readonly prisma: PrismaService) { }

    create(createVisitDto: CreateVisitDto) {
        return this.prisma.visit.create({
            data: createVisitDto
        })
    }

    async findAll(query: { country?: string, province?: string, city?: string, pageIndex: number, pageSize: number }) {
        const list = await this.prisma.visit.findMany({
            where: {
                country: query.country,
                province: query.province,
                city: query.city
            },
            skip: (query.pageIndex - 1) * query.pageSize,
            take: query.pageSize,
            orderBy: { createTime: 'desc' }
        })
        const total = await this.prisma.visit.count({
            where: {
                country: query.country,
                province: query.province,
                city: query.city
            }
        })
        return { list, total }
    }

    findOne(id: number) {
        return this.prisma.visit.findUnique({
            where: { id }
        })
    }

    findOneOfIP(ip: string) {
        return this.prisma.visit.findUnique({
            where: { ip }
        })
    }

    update(id: number, updateVisitDto: UpdateVisitDto) {
        return this.prisma.visit.update({
            where: { id },
            data: updateVisitDto
        })
    }

    remove(id: number) {
        return this.prisma.visit.delete({
            where: { id }
        })
    }

    upsert (ip: string, createVisitDto: CreateVisitDto) {
        return this.prisma.visit.upsert({
            where: { ip },
            create: createVisitDto,
            update: {}
        })
    }
}
